package org.lib.data.user.service.impl;

import java.util.Objects;

import org.lib.data.user.api.dto.AddUserDTO;
import org.lib.data.user.api.dto.UpdateUserDTO;
import org.lib.data.user.entity.User;
import org.lib.data.user.repo.UserDAO;
import org.lib.data.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户接口实现类：MySQL
 * @author ben
 * @date 2021-08-30 21:59:53 CST
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDAO userDao;

	private final static String USER_CACHE_VALUE = "data.user";
	// key 的 单引号 必须有！
	private final static String USER_CACHE_KEY = "'user'";
	
	@Override
	@CacheEvict(value=USER_CACHE_VALUE, key=USER_CACHE_KEY)
	public Long addUser(AddUserDTO dto) {
//		User nuser = new User(dto.getName(), dto.getSex(), dto.getAge());
		// 安全版
		User nuser = new User(dto.getName(), dto.getSex(), dto.getAge(),
				dto.getNickName(), dto.getPassword(), dto.getPhone(), dto.getEmail());
		User savedUser = userDao.save(nuser);
		log.info("添加用户成功：id={}", savedUser.getId());
		return savedUser.getId();
	}

	@Override
	@Cacheable(value=USER_CACHE_VALUE, key="'user_' + #id", unless="#result == null")
	public User getById(Long id) {
		Objects.requireNonNull(id);
		
		return userDao.findById(id).orElse(null);
	}

	@Override
	@CacheEvict(value = USER_CACHE_VALUE, key="'user_' + #id")
	public Boolean delById(Long id) {
		Objects.requireNonNull(id);
		
		// 删除
		// 先判断，然后再执行，否则，发生异常
		if (userDao.existsById(id)) {
			userDao.deleteById(id);
		}
		
		return userDao.existsById(id);
	}

	@Override
	public User getByEmail(String email) {
		if (!StringUtils.hasText(email)) {
			return null;
		}
		
		return userDao.findByEmail(email);
	}

	@Override
	public User getByPhone(String phone) {
		if (!StringUtils.hasText(phone)) {
			return null;
		}
		
		return userDao.findByPhone(phone);
	}

	@Override
	@CachePut(value = USER_CACHE_VALUE, key="'user_' + #dto.getId()")
	public User updateUser(UpdateUserDTO dto) {
		Long id = dto.getId();
		if (Objects.isNull(id)) {
			log.debug("参数错误：id is null");
			return null;
		}
		
		User oldUser = userDao.findById(id).orElse(null);
		if (Objects.isNull(oldUser)) {
			log.warn("更新的用户不存在：id={}", id);
			return null;
		}

		log.info("更新前的user={}", oldUser);
		boolean needUpdate = this.modifyOldUser(oldUser, dto);
		if (!needUpdate) {
			return null;
		}
		
		log.info("更新后的user={}", oldUser);
		User updatedUser = userDao.saveAndFlush(oldUser);
		log.info("更新后的updatedUser={}", updatedUser);
		return updatedUser;
	}

	/**
	 * 使用dto的数据更新
	 * @author ben
	 * @date 2021-09-02 22:43:50 CST
	 * @param oldUser
	 * @param dto
	 * @return
	 */
	private boolean modifyOldUser(User oldUser, final UpdateUserDTO dto) {
		boolean needUpdate = false;
		
		String nickName = dto.getNickName();
		if (StringUtils.hasText(nickName)) {
			oldUser.setNickName(nickName);
			needUpdate = true;
		}
		
		// TODO update more fileds
		
		return needUpdate;
	}

}
